package com.cwf.framework.authcode.service.impl;

import com.alibaba.fastjson2.JSON;
import com.cwf.common.enums.ResCodeEnum;
import com.cwf.common.exception.base.MyException;
import com.cwf.common.utils.id.IdUtil;
import com.cwf.framework.authcode.entity.KaptchaImageCodeEntity;
import com.cwf.framework.authcode.service.KaptchaService;
import com.cwf.framework.redis.RedisService;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class KaptchaServiceImpl implements KaptchaService {


    private String mark ="Kaptcha:";


    @Autowired
    DefaultKaptcha defaultKaptcha;


    @Autowired
    RedisService redisTemplate;


    @Override
    public KaptchaImageCodeEntity generateImageCode() throws IOException {


        ByteArrayOutputStream out;
        //生成UUID
        String key = IdUtil.randomUUID();
        //生成验证码
        String text = defaultKaptcha.createText();

        BufferedImage image = defaultKaptcha.createImage(text);

        out = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", out);
        BASE64Encoder base64Encoder = new BASE64Encoder();


        log.info("\n生成验证码{}\nuuid: {}", text,key);

        String redisKey = mark + key;

        try {
            redisTemplate.setCacheObject(redisKey, text, 300, TimeUnit.SECONDS);
        } catch (Exception e) {
            throw new MyException("验证码获取失败", 400);
        }

        //生成验证码信息
        KaptchaImageCodeEntity codeEntity = KaptchaImageCodeEntity.builder()
                .uuid(key)
                .image("data:image/jpg;base64," + base64Encoder.encode(out.toByteArray()).trim().replace("\n", "").replace("\r", ""))
                .build();

        return codeEntity;
    }


    @Override
    public boolean checkImageCode(String uuid, String code) {

        String key = mark + uuid;

        String redisCode = redisTemplate.getCacheObject(key);

        log.info("\n前台验证码: {}", code);
        log.info("\nredis验证码:{}", redisCode);


        if (redisCode == null){
            throw new MyException("验证码过期", ResCodeEnum.ERROR.getCode());
        }

        if (redisCode.equals(code)) {
            log.info("\n验证码检验成功");
            return true;
        } else {
            log.error("\n获取验证码失败");
            throw new MyException("验证码错误", ResCodeEnum.ERROR.getCode());
        }
    }
}
